<?php

defined('__VN_BASE') or define('__VN_BASE', dirname(__FILE__));

abstract class VNTemplate{

	private $vncore;

	public function __Construct(){}

	abstract public function loadHeaders();
	abstract public function getContent(string &$page, array &$array);

	public function __Destruct(){ unset($this); }

	/* Loads the VNCore config. */
	protected function loadConfig(array &$file){

		if(empty($file)){ return false; }
	
		$this->config = $file;

	}

	/* May not be best way to ask for template from user */
	protected function loadFile(array &$file, array $options){

		if(empty($file)){ return false; }

		foreach($file as $t => $list){

			/* $t - Type, $f - File */
			foreach($list as $f){

				/**
				 * If the file is an array, send the array as the options instead
				 * Built to handle meta data includes.
				 */
				//print_r($f);print"\r\n";
				if(is_array($f)){
					$str = $this->buildInclude(string($t),$f);
				}elseif($t == "fold"){
					$str = $this->getFilesInFolder($f,$options);
				}else{
					$str = $this->buildInclude(string($t),$options);
				}

				$arr[] = sprintf($str,$f);

			}

		}

		return $arr;

	}

	private function buildInclude(string &$type, array &$options){

		switch($type){

			case "css":
				return "<link rel='stylesheet' href='".$this->vncore['VNSite']."/template/".$options['template']."/css/%s' />";
				break;
			case "js":
				return "<script src='".$this->vncore['VNSite']."/template/".$options['template']."/js/%s'></script>";
				break;
			case "meta":
				return "<meta name='".$options[0]."' content='".$options[1]."' />";
				break;
			case "fold":
				return $this->getFilesInFolder( string($options['template']) );
				break;
			default:
				return "";

		}

	}

	private function getFilesInFolder($folder, array &$options){

		$dir = "/web/sites/chaf/template/".$options['template']."/".$folder."/";
		if(!is_dir($dir)){ return NULL; }

		$str = string("");
		if($dh = opendir($dir)){

			//$files = array();
			while (($file = readdir($dh)) !== false) {
				
				/* Skip any files which could be directories */
				if($file == "." || $file == ".." || $file[0] == "."){ continue; }

				/* Skip any file which does not match extension to folder */
				if($folder !== pathinfo($file, PATHINFO_EXTENSION)){ continue; }

				$files[] = $file;

			}
			sort($files);

		}

		foreach($files as $file){

			$ext = pathinfo($file, PATHINFO_EXTENSION);
			$item = sprintf($this->buildInclude( string($ext), $options ),$file);
			$str .= $item."\r\n";

		}

		return $str;
		

	}

};
